package com.example.controller;

import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.cluster.health.ClusterHealthStatus;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest;
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/es")
public class EsTestController {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @GetMapping("/health")
    public Map<String, Object> getClusterHealth() throws IOException {
        ClusterHealthRequest request = new ClusterHealthRequest();
        ClusterHealthResponse response = restHighLevelClient.cluster().health(request, RequestOptions.DEFAULT);
        
        Map<String, Object> result = new HashMap<>();
        result.put("status", response.getStatus().name());
        result.put("numberOfNodes", response.getNumberOfNodes());
        result.put("numberOfDataNodes", response.getNumberOfDataNodes());
        result.put("activeShards", response.getActiveShards());
        result.put("activePrimaryShards", response.getActivePrimaryShards());
        
        return result;
    }
    
    @GetMapping("/indices")
    public Map<String, Object> getIndices() throws IOException {
        GetIndexRequest request = new GetIndexRequest("*");
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        
        Map<String, Object> result = new HashMap<>();
        if (exists) {
            String[] indices = restHighLevelClient.indices().get(request, RequestOptions.DEFAULT).getIndices();
            result.put("indices", Arrays.asList(indices));
        } else {
            result.put("indices", "No indices found");
        }
        
        return result;
    }
} 